const fs = require('fs').promises;
const path = require('path');
const { processCommonListTemplate } = require('./commonListService');
const { processDetailTemplate } = require('./detailService');
const { processModalTemplate } = require('./modalService');
const { processMultiTabDetailTemplate } = require('./multiTabDetailService');

// 模板处理器映射
const templateProcessors = {
  'commonList': processCommonListTemplate,
  'detail': processDetailTemplate,
  'modal_table': processModalTemplate,
  'modal_form': processModalTemplate,
  'ldzh_list': processCommonListTemplate,
  'ldzh_detail': processDetailTemplate,
  'multi_tab_detail': processMultiTabDetailTemplate,
};

/**
 * 获取模板配置
 * @param {string} templateType - 模板类型
 * @param {Object} dataSourceConfig - 数据源配置
 * @returns {Object} 模板配置参数
 */
function getTemplateConfig(templateType, dataSourceConfig) {
  const config = {
    queryFields: dataSourceConfig.queryFields || [],
    listFields: dataSourceConfig.listFields || [],
    headerFields: dataSourceConfig.headerFields || [],
    detailQueryFields: dataSourceConfig.detailQueryFields || [],
    detailListFields: dataSourceConfig.detailListFields || [],
    detailFormFields: dataSourceConfig.detailFormFields   || dataSourceConfig.detailListFields  || [],
  };

  switch (templateType) {
    case 'commonList':
      return {
        templateType:templateType,
        ...config,
        vueFileName: 'list.vue',
        useCompositionAPI: true
      };
    case 'modal_table':
      return {
        templateType:templateType,
        ...config
      };
    case 'modal_form':
      return {
        templateType:templateType,
        ...config,
        formFields: dataSourceConfig.formFields || [],
      };
    case 'detail':
      return {
        templateType:templateType,
        ...config,
        vueFileName: 'detail.vue',
        useCompositionAPI: true
      };
    case 'ldzh_list':
      return {
        templateType: 'commonList',
        ...config,
        vueFileName: 'list.vue',
        useCompositionAPI: true
      };
    case 'ldzh_detail':
      return {
        templateType: 'detail',
        ...config,
        vueFileName: 'detail.vue',
        useCompositionAPI: true
      };
    case 'multi_tab_detail':
      return {
        templateType:templateType,
        ...config,
        vueFileName: 'detail.vue',
        useCompositionAPI: true
      };
    default:
      throw new Error(`Unsupported template type: ${templateType}`);
  }
}

/**
 * 根据前端传来的数据生成代码
 * @param {Object} data - 前端传来的数据
 * @param {string} templateType - 模板类型 ('commonList' 或 'detail')
 * @param {string} tempDir - 临时目录路径
 * @param {Object} res - Express响应对象
 * @returns {Promise<string>} 生成的目录名
 */
async function generateCodeFromData(data, templateType, tempDir, res, dirName) {
  // 解析数据
  const dataSourceConfig = data.dataSourceConfig || {};

  // 根据模板类型获取配置参数
  const templateConfig = getTemplateConfig(templateType, dataSourceConfig);

  // 创建目录结构
  let targetDir = tempDir;
  if (dirName) {
    // 正则判断是否包含 /
    const dirParts = dirName.split('/');
    targetDir = path.join(targetDir, ...dirParts);
  } else {
    targetDir = path.join(tempDir, templateType);
  }

  const hooksDir = path.join(targetDir, 'hooks');
  await fs.mkdir(targetDir, { recursive: true });
  await fs.mkdir(hooksDir, { recursive: true });

  // 根据模板类型使用不同的处理器
  const processor = templateProcessors[templateType];
  if (processor) {
    await processor(data, templateConfig, targetDir, hooksDir, res);
  } else {
    throw new Error(`Unsupported template type: ${templateType}`);
  }

  return dirName ?? templateType;
}

module.exports = {
  generateCodeFromData,
  getTemplateConfig
};